// PositionServiceImpl.java
package com.zyp.jobseeker.service.impl;

import com.zyp.jobseeker.entity.Position;
import com.zyp.jobseeker.enums.PositionStatus;
import com.zyp.jobseeker.mapper.PositionMapper;
import com.zyp.jobseeker.service.PositionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 岗位服务实现类
 */
@Service
public class PositionServiceImpl implements PositionService {
    // 添加日志记录器
    private static final Logger logger = LoggerFactory.getLogger(PositionServiceImpl.class);

    @Autowired
    private PositionMapper positionMapper;

    @Override
    @Transactional
    public Long publishPosition(Long enterpriseId, Map<String, Object> positionData) {
        try {
            logger.info("发布新岗位，企业ID: {}", enterpriseId);
            logger.debug("岗位数据: {}", positionData);

            Position position = new Position();
            position.setEnterpriseId(enterpriseId);
            position.setPositionName((String) positionData.get("positionName"));
            position.setResponsibility((String) positionData.get("responsibility"));
            position.setRequirement((String) positionData.get("requirement"));
            position.setSalaryRange((String) positionData.get("salaryRange"));
            position.setRecruitmentNum((Integer) positionData.get("recruitmentNum"));
            position.setWorkLocation((String) positionData.get("workLocation"));
            position.setStatus(PositionStatus.PUBLISHED);  // 设置为已发布状态
//            position.setCreateTime(LocalDateTime.now());
//            position.setLastUpdateTime(LocalDateTime.now());

            // 调用mapper插入岗位
            positionMapper.insertPosition(position);
            //从数据库中
            logger.info("岗位插入成功，生成岗位ID: {}", position.getId());
            return position.getId();
        } catch (Exception e) {
            logger.error("岗位发布失败", e);
            throw new RuntimeException("岗位发布失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean updatePosition(Long id, Map<String, Object> updateData, Long enterpriseId) {
        try {
            logger.info("更新岗位信息，岗位ID: {}", id);
            logger.debug("更新数据: {}", updateData);

            Position position = positionMapper.selectById(id);

            // 验证岗位是否存在且属于当前企业
            if (position == null || !position.getEnterpriseId().equals(enterpriseId)) {
                logger.warn("岗位更新失败，岗位ID: {} 不存在或不属于当前企业", id);
                return false;
            }

            // 动态更新字段
            if (updateData.containsKey("responsibility")) {
                position.setResponsibility((String) updateData.get("responsibility"));
                logger.debug("更新岗位职责: {}", position.getResponsibility());
            }
            if (updateData.containsKey("requirement")) {
                position.setRequirement((String) updateData.get("requirement"));
                logger.debug("更新任职要求: {}", position.getRequirement());
            }
            if (updateData.containsKey("salaryRange")) {
                position.setSalaryRange((String) updateData.get("salaryRange"));
                logger.debug("更新薪资范围: {}", position.getSalaryRange());
            }
            if (updateData.containsKey("recruitmentNum")) {
                position.setRecruitmentNum((Integer) updateData.get("recruitmentNum"));
                logger.debug("更新招聘人数: {}", position.getRecruitmentNum());
            }
            if (updateData.containsKey("workLocation")) {
                position.setWorkLocation((String) updateData.get("workLocation"));
                logger.debug("更新工作地点: {}", position.getWorkLocation());
            }

//            // 更新最后修改时间
//            position.setLastUpdateTime(LocalDateTime.now());
//            logger.debug("更新最后修改时间: {}", position.getLastUpdateTime());

            // 调用mapper更新岗位
            boolean success = positionMapper.updatePosition(position) > 0;
            if (success) {
                logger.info("岗位信息更新成功，岗位ID: {}", id);
            } else {
                logger.warn("岗位信息更新失败，岗位ID: {}", id);
            }
            return success;
        } catch (Exception e) {
            logger.error("岗位更新失败，岗位ID: {}", id, e);
            throw new RuntimeException("岗位更新失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean deprecatePosition(Long id, Long enterpriseId) {
        try {
            logger.info("废除岗位，岗位ID: {}", id);
            logger.debug("企业ID: {}", enterpriseId);

            // 调用mapper废除岗位
            boolean success = positionMapper.deprecatePosition(Map.of("id", id, "enterpriseId", enterpriseId)) > 0;

            if (success) {
                logger.info("岗位废除成功，岗位ID: {}", id);
            } else {
                logger.warn("岗位废除失败，岗位ID: {}, 原因: 没有权限或岗位不存在", id);
            }
            return success;
        } catch (Exception e) {
            logger.error("岗位废除失败，岗位ID: {}", id, e);
            throw new RuntimeException("岗位废除失败: " + e.getMessage());
        }
    }

    @Override
    public PageInfo<Position> getEnterprisePositions(Long enterpriseId, int pageNum, int pageSize) {
        try {
            logger.info("查询企业岗位列表，企业ID: {}", enterpriseId);
            logger.debug("分页参数: pageNum={}, pageSize={}", pageNum, pageSize);

            // 启动分页
            PageHelper.startPage(pageNum, pageSize);

            // 查询岗位列表
            List<Position> positions = positionMapper.selectByEnterpriseId(enterpriseId);

            // 返回PageInfo结果
            PageInfo<Position> pageInfo = new PageInfo<>(positions);
            logger.info("企业岗位查询成功，总记录数: {}", pageInfo.getTotal());
            return pageInfo;
        } catch (Exception e) {
            logger.error("企业岗位查询失败，企业ID: {}", enterpriseId, e);
            throw new RuntimeException("企业岗位查询失败: " + e.getMessage());
        }
    }

    @Override
    public PageInfo<Position> searchPositions(String keyword, int pageNum, int pageSize) {
        try {
            logger.info("搜索岗位，关键字: {}", keyword == null ? "无" : keyword);
            logger.debug("分页参数: pageNum={}, pageSize={}", pageNum, pageSize);

            // 启动分页
            PageHelper.startPage(pageNum, pageSize);

            // 查询岗位列表
            List<Position> positions = positionMapper.searchPositions(keyword);

            // 返回PageInfo结果
            PageInfo<Position> pageInfo = new PageInfo<>(positions);
            logger.info("岗位搜索成功，返回记录数: {}", pageInfo.getList().size());
            return pageInfo;
        } catch (Exception e) {
            logger.error("岗位搜索失败，关键字: {}", keyword == null ? "无" : keyword, e);
            throw new RuntimeException("岗位搜索失败: " + e.getMessage());
        }
    }

    @Override
    public Position getPositionById(Long id) {
        try {
            logger.info("获取岗位信息，岗位ID: {}", id);

            // 查询岗位详情
            Position position = positionMapper.selectById(id);

            // 验证岗位是否存在
            if (position == null) {
                logger.warn("岗位不存在，岗位ID: {}", id);
                throw new RuntimeException("岗位不存在");
            }

            logger.debug("成功获取岗位信息: {}", position.getPositionName());
            return position;
        } catch (Exception e) {
            logger.error("岗位查询失败，岗位ID: {}", id, e);
            throw new RuntimeException("岗位查询失败: " + e.getMessage());
        }
    }
}
